package com.cet.others;

/**
 * @program: algorithm
 * @description: 牛顿迭代法 g(x) = x^2-n,第一象限函数g(x)上任取一点(x0,g(x0))，过该点作函数g(x)切线，与x轴交点记为x1，……，当xn与xn+1的距离在误差允许范围之内，xn+1就可以视为根
 * @author: 陈恩涛
 * @create: 2020-11-30 12:24
 **/
public class Newton {

    public static double newton(double n){
        double x0 = 1.0;
        double t;
        double err = 1e-15;

        t= x0 - (x0*x0 - n)/(2*x0);
        while (Math.abs(t - x0) > err) {
            x0 = t;
            t = x0 - (x0 * x0 - n) / (2 * x0);
        }
        return t;
    }

    public static void main(String[] args) {
        System.out.println(newton(2));
    }
}
